package com.uton.rfidcontroller.view.base;

import android.app.Dialog;
import android.content.pm.ActivityInfo;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.uton.rfidcontroller.R;
import com.uton.rfidcontroller.common.intent.IntentBuilder;
import com.uton.rfidcontroller.common.interfaces.INetController;
import com.uton.rfidcontroller.common.interfaces.IPublicController;
import com.uton.rfidcontroller.common.net.RetrofitFactory;
import com.uton.rfidcontroller.common.utils.SharedPreferencesUtils;
import com.uton.rfidcontroller.common.utils.Utils;
import com.uton.rfidcontroller.view.activity.LoginActivity;
import com.uton.rfidcontroller.viewmodel.base.BaseViewModel;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 王家宝 on 2017/8/30.
 * Email:639586819@qq.com
 * Tel:18241150668
 */
public abstract class BaseActivity<VDB extends ViewDataBinding, VM extends BaseViewModel>
        extends RxAppCompatActivity implements IPublicController.INetController {

    protected VDB mBinding;

    protected VM mViewModel;

    //左上角返回
    @Nullable
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    //右侧功能
    @Nullable
    @BindView(R.id.ll_right_setting)
    LinearLayout llRightSetting;
    //中间图片
    @Nullable
    @BindView(R.id.iv_main_title)
    ImageView ivMainTitle;
    //中间文字
    @Nullable
    @BindView(R.id.tv_main_title)
    TextView tvMainTitle;

    //是否显示TitleBar中间的图片
    private boolean isShowCenterImage;
    //是否显示右侧功能区
    private boolean isShowRightSetting;

    protected Unbinder mBind;

    private TextView mTipTextView;


    /**
     * 初始化dataBinding
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //禁止横屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //初始化Dialog
        initDialog();
        //初始化数据绑定
        initDataBinding();
        //Butterknife
        mBind = ButterKnife.bind(this);
        //初始化
        mViewModel = setViewModel();
        inject();
        //初始化base title ;
        initBaseLayout();
        //做其他的事
        doSomething();
    }

    private void initDialog() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View v = inflater.inflate(R.layout.dialog_loading_ori, null);// 得到加载view
        LinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view);// 加载布局
        // main.xml中的ImageView
        // 提示文字
        mTipTextView = (TextView) v.findViewById(R.id.tipTextView);
        // 创建自定义样式dialog
        mDialog = new Dialog(this, R.style.loading_dialog);
        mDialog.setContentView(layout, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.FILL_PARENT));// 设置布局
    }

    private void initBaseLayout() {
        if (llBack != null) {
            llBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    doOnFinish();
                    finish();
                }
            });
        }

        if (llRightSetting != null) {
            if (isShowRightSetting) {
                llRightSetting.setVisibility(View.VISIBLE);
            } else {
                llRightSetting.setVisibility(View.INVISIBLE);
            }

        }

        if (ivMainTitle != null) {
            if (isShowCenterImage()) {
                ivMainTitle.setVisibility(View.VISIBLE);
                tvMainTitle.setVisibility(View.GONE);
            } else {
                ivMainTitle.setVisibility(View.GONE);
                tvMainTitle.setVisibility(View.VISIBLE);
                tvMainTitle.setText(setTitle() != null ? setTitle() : getString(R.string.ui_title_common));
            }
        }


    }

    /**
     * 空方法，必要时重写该方法写入返回码
     */
    protected void doOnFinish(){
    }

    //注入布局
    private void initDataBinding() {
        mBinding = DataBindingUtil.setContentView(this, setLayout());
    }

    protected abstract int setLayout();

    protected abstract void inject();

    protected abstract String setTitle();

    protected abstract void doSomething();

    public void logOut() {
        showProgressDialog(null, false);
        getViewModel().go(RetrofitFactory.getInstance().logout(new HashMap<String, Object>()), new INetController<String>() {
            @Override
            public void onSuccess(String response) {
                Utils.showShortToast("退出成功");
                disDialog();
                SharedPreferencesUtils.clearToken();
                SharedPreferencesUtils.clearUserID();
                // TODO: 2017/9/29 关闭所有页面，回到登录页面
                naviToLogin();
            }

            @Override
            public void onError() {
                Utils.showShortToast("退出失败");
                disDialog();
                SharedPreferencesUtils.clearToken();
                SharedPreferencesUtils.clearUserID();
                // TODO: 2017/9/29 关闭所有页面，回到登录页面
                naviToLogin();
            }

            @Override
            public void onComplete() {
                disDialog();
            }

            private void naviToLogin() {
                startActivity(new IntentBuilder().from(getCurrentActivity(), LoginActivity.class).getIntent());
                finish();
            }

        });
    }

    /**
     * 强制开启右侧功能
     */
    public void showRightSetting() {
        if (llRightSetting != null) {
            llRightSetting.setVisibility(View.VISIBLE);
            llRightSetting.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // TODO: 2017/9/29 退出登录
                    logOut();
                }
            });
        }
    }

    /**
     * 获取当前Activity
     */
    public BaseActivity<VDB, VM> getCurrentActivity() {
        return this;
    }


    /**
     * 设置viewModel
     */
    public VDB getBinding() {
        return mBinding;
    }

    public VM getViewModel() {
        return mViewModel;
    }

    protected abstract VM setViewModel();

    public boolean isShowCenterImage() {
        return isShowCenterImage;
    }

    public void setShowCenterImage(boolean showCenterImage) {
        isShowCenterImage = showCenterImage;
    }

    /**
     * 添加线程调度
     */
    public <T> ObservableTransformer<T, T> compose(final LifecycleTransformer<T> lifecycle) {
        return new ObservableTransformer<T, T>() {
            @Override
            public ObservableSource<T> apply(Observable<T> observable) {
                return observable
                        .subscribeOn(Schedulers.io())
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Exception {
                                if (!Utils.isNetworkAvailable(BaseActivity.this)) {
                                    Utils.showShortToast(getString(R.string.toast_network_error));
                                }
                            }

                        })
                        .observeOn(AndroidSchedulers.mainThread())
                        .compose(lifecycle);
            }
        };
    }

    @Override
    public void doOnResponse(int doType) {

    }


    private Dialog mDialog;


    public void showProgressDialog(String msg, boolean isCanceled) {
        if (msg != null) {
            mTipTextView.setText(msg);
        }
        mDialog.setCancelable(isCanceled);// 设定是否可以取消
        mDialog.show();
    }

    public void disDialog() {
        mDialog.dismiss();
    }


    @Override
    protected void onDestroy() {
        if (mBinding != null){
            mBinding.unbind();
        }
        mBind.unbind();
        super.onDestroy();
    }

}
